package com.avricot.userinfo;

import com.avricot.userinfo.browser.Browser;
import com.avricot.userinfo.browser.BrowserName;
import com.avricot.userinfo.os.OS;
import com.avricot.userinfo.os.OSName;

public class UserInfo {
    public static final String VERSION_UNKNOWN = "unkown";

    /**
     * Return the Browser for a given userAgent. If now browser can be find, Unkown browser is
     * returned.
     */
    public static Browser getBrowser(final String userAgent) {
	if (userAgent == null) {
	    throw new NullPointerException("userAgent can't be null");
	}
	String browserVersion;
	for (final BrowserName browserName : BrowserName.values()) {
	    browserVersion = browserName.getVersion(userAgent);
	    if (browserVersion != null) {
		return new Browser(browserName, browserVersion);
	    }
	}
	throw new IllegalAccessError("default OS should be returned, getOS isn't suposed to return null.");
    }

    /**
     * Return the OS for a given userAgent. If no OS can be find, Unknown os is returned.
     */
    public static OS getOS(final String userAgent) {
	if (userAgent == null) {
	    throw new NullPointerException("userAgent can't be null");
	}
	String OsVersion;
	for (final OSName OsName : OSName.values()) {
	    OsVersion = OsName.getVersion(userAgent);
	    if (OsVersion != null) {
		return new OS(OsName, OsVersion);
	    }
	}
	throw new IllegalAccessError("default OS should be returned, getOS isn't suposed to return null.");
    }

    /**
     * Return true when the given userAgent match with a specific browserName.
     */
    public static boolean isBrowser(final String userAgent, final BrowserName browserName) {
	if (userAgent == null) {
	    throw new NullPointerException("userAgent can't be null");
	}
	return browserName.getVersion(userAgent) != null;
    }

    /**
     * Return true when the given userAgent match with a specific OSName.
     */
    public static boolean isOS(final String userAgent, final OSName osName) {
	if (userAgent == null) {
	    throw new NullPointerException("userAgent can't be null");
	}
	return osName.getVersion(userAgent) != null;
    }

    /**
     * Build and return a UserInfo for a given userAgent.
     */
    public static UserInfo getUserInfo(final String userAgent) {
	return new UserInfo(getOS(userAgent), getBrowser(userAgent));
    }

    private OS os;
    private Browser browser;

    public UserInfo() {

    }

    public UserInfo(final OS os, final Browser browser) {
	this.browser = browser;
	this.os = os;

    }

    public OS getOs() {
	return os;
    }

    public void setOs(final OS os) {
	this.os = os;
    }

    public Browser getBrowser() {
	return browser;
    }

    public void setBrowser(final Browser browser) {
	this.browser = browser;
    }

    @Override
    public String toString() {
	return "UserInfo [os=" + os + ", browser=" + browser + "]";
    }

}
